<template>
  <a-popover trigger="click" :popup-visible="visible">
    <template #content>
      <a-space ref="target" :size="12">
        <a-input
          v-model="inputValue"
          :max-length="limit"
          show-word-limit
          :placeholder="placeholder"
        />
        <a-button type="text" @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleConfirm">确定</a-button>
      </a-space>
    </template>
    <div class="trigger-box" @click="toggleVisible">
      <slot>
        <a-button>新建</a-button>
      </slot>
    </div>

  </a-popover>
</template>

<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { onClickOutside } from "@vueuse/core";


const visible = ref(false);

const toggleVisible = () => {
  nextTick(() => {
    visible.value = !visible.value;
  });
};
// 内部 value
const inputValue = ref();


const props = withDefaults(defineProps<{
  modelValue?: string
  placeholder?: string
  limit?: string | number
}>(), {
  modelValue: "",
  placeholder: "请输入...", // simple
  limit: 50
});

watch(
  () => props.modelValue,
  (value) => {
    inputValue.value = value;
  },
  {
    immediate: true
  }
);

const emit = defineEmits(["confirm"]);

const handleConfirm = () => {
  emit("confirm", inputValue.value);
  visible.value = false;
};

const handleCancel = () => {
  inputValue.value = props.modelValue;
  visible.value = false;
};

// 点击外部隐藏
const target = ref();
onClickOutside(target, (event) => {
  console.log(event);
  handleCancel();
});
</script>

<style scoped lang="less">
.trigger-box {
  display: inline-flex;
}
</style>
